package com.example.interesting.distributed.lock.realize.strategy;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author fyw
 * @version 1.0
 * @description: 分布式锁默认执行器逻辑，基于redisson
 * @date 2024/3/16 13:26
 */
@Slf4j
@AllArgsConstructor
public class DefaultDistributedLockExecutorStrategy implements DistributedLockExecutorStrategy<RLock> {


    private final RedissonClient redissonClient;

    @Override
    public RLock acquireLock(String key, long acquireTimeout, long expireTime) {
        //获取redisson分布式锁实例
        try {
            RLock lockInstance = redissonClient.getLock(key);
            //获取分布式锁
            final boolean acquireResult = lockInstance.tryLock(acquireTimeout, expireTime, TimeUnit.MILLISECONDS);
            return acquireResult ? lockInstance : null;
        } catch (InterruptedException e) {
            log.error("获取分布式锁获取锁逻辑异常key：{}", key, e);
        }
        return null;
    }

    @Override
    public boolean releaseLock(RLock lockInstance) {
        //锁释放逻辑
        if (lockInstance.isHeldByCurrentThread()) {
            //当前线程
            try {
                lockInstance.unlockAsync().get();
                return true;
            } catch (InterruptedException | ExecutionException e) {
                log.error("释放分布式锁获取锁逻辑异常key：{}", lockInstance.getName(), e);
                return false;
            }
        }
        return false;
    }
}
